import Taro from '@tarojs/taro'
import { getAppletTemplates, postSubsetting } from '@/api/subscribe'
import config from '_config/index'
import store from '@/store/index'

// 是否开启订阅开关
export function getSubscribeSwitch() {
  return new Promise((resolve) => {
    Taro.getSetting({
      withSubscriptions: true,
      success: (settingRes) => {
        console.log('弹窗订阅获取设置结果=====', settingRes)
        if (settingRes.subscriptionsSetting.mainSwitch) {
          resolve(true)
        } else {
          // 总开关关闭，啥都不用干
          resolve(false)
        }
      },
      fail: (err) => {
        console.log('弹窗订阅获取设置失败=====', err)
        resolve(false)
      }
    })
  })
}

// 获取开启订阅页需要的订阅信息(不订阅弹窗)
export function getSubscribeTemplates(callback) {
  return new Promise((resolve) => {
    getAppletTemplates().then((res1) => {
      if (res1?.success) {
        if (res1.data?.length <= 0) {
          resolve(false)
        } else {
          Taro.getSetting({
            withSubscriptions: true,
            success: (settingRes) => {
              console.log('弹窗订阅获取设置结果=====', settingRes)

              if (settingRes.subscriptionsSetting.mainSwitch) {
                const itemSettings = settingRes.subscriptionsSetting?.itemSettings || {}
                // 总开关开启，继续下一步，筛选合适的模板
                const keys = Object.keys(itemSettings)

                // 拿取所有模版
                const obj = res1.data.filter((item) => item?.templateType === 'Edu')
                let templateList = []
                if (obj && obj?.length > 0) {
                  templateList = obj[0]?.templateList
                }
                // 存下edu模版
                store.user.setSubscriptionTemplateListEdu(templateList)

                // 去除已订阅的模版
                const tempList = templateList?.filter((item) => !keys.includes(item?.id))
                // 已订阅的模版 (订阅包含拒绝和同意)
                const tempList2 = templateList?.filter((item) => keys.includes(item?.id))

                // 所以已拒绝的订阅模版
                const tempList3 = []
                tempList2.forEach((item) => {
                  if (item?.id && itemSettings[item?.id]) {
                    if (itemSettings[item.id] === 'reject') {
                      tempList3.push(item.id)
                    }
                  }
                })
                // 判断是否全部已拒绝
                let isRejectAll = false
                if (tempList3?.length > 0 && tempList3?.length === templateList?.length) {
                  isRejectAll = true
                }

                console.log('tempList===', tempList)
                const templateNames = []
                if (tempList?.length > 0) {
                  templateNames.push(tempList[0].name)
                }
                callback && callback(templateList, templateNames, isRejectAll)
              }
            },
            fail: (err) => {
              console.log('弹窗订阅获取设置失败=====', err)
              resolve(false)
            }
          })
        }
      } else {
        Taro.hideLoading()
        resolve(false)
      }
    })
  })
}

// 开启订阅(订阅弹窗)
export function openSubscribe(callback) {
  Taro.showLoading()
  return new Promise((resolve) => {
    getAppletTemplates().then((res1) => {
      Taro.hideLoading()
      if (res1?.success) {
        if (res1.data?.length <= 0) {
          resolve(false)
        } else {
          Taro.getSetting({
            withSubscriptions: true,
            success: (settingRes) => {
              console.log('弹窗订阅获取设置结果=====', settingRes)

              if (settingRes.subscriptionsSetting.mainSwitch) {
                // 总开关开启，继续下一步，筛选合适的模板
                const keys = Object.keys(settingRes.subscriptionsSetting?.itemSettings || {})
                // 拿取所有模版
                const obj = res1.data.filter((item) => item?.templateType === 'Edu')
                let templateList = []
                if (obj && obj?.length > 0) {
                  templateList = obj[0]?.templateList
                }
                // 去除已订阅的模版
                const tempList = templateList?.filter((item) => !keys.includes(item?.id))
                console.log('tempList===', tempList)
                if (tempList?.length > 0) {
                  // 继续下一步
                  const templateIds = []
                  const templateNames = []
                  // tempList.forEach((item) => {
                  //   templateIds.push(item.id)
                  //   templateNames.push(item.name)
                  // })
                  templateIds.push(tempList[0].id)
                  templateNames.push(tempList[0].name)

                  // 在这里开始弹窗订阅
                  // 弹窗
                  callback && callback(templateNames)
                  // 订阅
                  requestSubscribe(templateIds).then((result) => {
                    console.log('弹窗订阅结果=====', result)
                    reportSubscriptionsSetting(result)
                    resolve(result)
                  })
                } else {
                  resolve(false)
                }
              } else {
                // 总开关关闭，啥都不用干
                resolve(false)
              }
            },
            fail: (err) => {
              console.log('弹窗订阅获取设置失败=====', err)
              resolve(false)
            }
          })
        }
      } else {
        Taro.hideLoading()
        resolve(false)
      }
    })
  })
}

// 开启订阅(订阅弹窗)(已先获取了模版列表)
export function openSubscribeWithList(callback, templateList) {
  return new Promise((resolve) => {
    Taro.getSetting({
      withSubscriptions: true,
      success: (settingRes) => {
        console.log('弹窗订阅获取设置结果=====', settingRes)

        if (settingRes.subscriptionsSetting.mainSwitch) {
          // 总开关开启，继续下一步，筛选合适的模板
          const keys = Object.keys(settingRes.subscriptionsSetting?.itemSettings || {})
          // 拿取所有模版
          // const obj = res1.data.filter((item) => item?.templateType === 'Edu')
          // let templateList = []
          // if (obj && obj?.length > 0) {
          //   templateList = obj[0]?.templateList
          // }
          // 去除已订阅的模版
          const tempList = templateList?.filter((item) => !keys.includes(item?.id))
          console.log('tempList===', tempList)
          if (tempList?.length > 0) {
            // 继续下一步
            const templateIds = []
            const templateNames = []
            // tempList.forEach((item) => {
            //   templateIds.push(item.id)
            //   templateNames.push(item.name)
            // })
            templateIds.push(tempList[0].id)
            templateNames.push(tempList[0].name)

            // 在这里开始弹窗订阅
            // 弹窗
            callback && callback(templateNames)
            // 订阅
            requestSubscribe(templateIds).then((result) => {
              console.log('弹窗订阅结果=====22', result)
              // 点击了取消就不用刷新了
              reportSubscriptionsSetting(result)
              resolve(result)
            })
          } else {
            resolve(false)
          }
        } else {
          // 总开关关闭，啥都不用干
          resolve(false)
        }
      },
      fail: (err) => {
        console.log('弹窗订阅获取设置失败=====', err)
        resolve(false)
      }
    })
  })
}

/**
 * 去同步配置
 */
export function reportSubscriptionsSetting(isRefresh) {
  Taro.getSetting({
    withSubscriptions: true,
    success: async (res) => {
      const params = {
        mainSwitch: res?.subscriptionsSetting?.mainSwitch || false,
        itemSettings: res?.subscriptionsSetting?.itemSettings || {},
        appId: config.APP_ID
      }
      console.log('getSetting====', res)
      console.log('params====', params)
      const result = await postSubsetting(params)

      if (result?.success) {
        // 申请查看数据页，点击开启订阅需要刷新下页面
        if (isRefresh) {
          Taro.eventCenter.trigger('reportSubscriptionsFinish')
        }
      } else {
        Taro.showToast({ title: res?.msg || '网络异常，请稍后重试', icon: 'none' })
      }
    }
  })
}

// 静默订阅
export function startSilentSubscribe() {
  return new Promise((resolve) => {
    getAppletTemplates().then((res1) => {
      if (res1?.success) {
        // 在这里获取系统设置，看是否总开关开了，然后筛选模板
        if (res1.data?.length <= 0) {
          resolve(false)
        } else {
          Taro.getSetting({
            withSubscriptions: true,
            success: (settingRes) => {
              console.log('订阅获取设置结果=====', settingRes)
              if (settingRes.subscriptionsSetting.mainSwitch) {
                // 总开关开启，继续下一步，筛选合适的模板
                // const keys = Object.keys(settingRes.subscriptionsSetting?.itemSettings || {})
                const keys = Object.keys(settingRes.subscriptionsSetting?.itemSettings || {})
                const acceptKeys = []
                keys.forEach((key) => {
                  if (settingRes.subscriptionsSetting[key] === 'accept') {
                    acceptKeys.push(key)
                  }
                })
                console.log('acceptKeys===', acceptKeys)

                // 拿取所有模版
                const obj = res1.data.filter((item) => item?.templateType === 'Edu')
                let templateList = []
                if (obj && obj?.length > 0) {
                  templateList = obj[0]?.templateList
                }
                // const tempList = templateList?.filter((item) => !keys.includes(item.templateId))
                const tempList = templateList.filter((item) => acceptKeys.includes(item.id))
                console.log('tempList===', tempList)

                if (tempList?.length > 0) {
                  const templateIds = []
                  tempList.forEach((item) => {
                    templateIds.push(item.id)
                  })
                  // 订阅
                  requestSubscribe(templateIds).then((result) => {
                    console.log('订阅结果=====', result)
                    reportSubscriptionsSetting()
                    resolve(result)
                  })
                } else {
                  resolve(false)
                }
              } else {
                // 总开关关闭，啥都不用干
                resolve(false)
              }
            },
            fail: (err) => {
              console.log('订阅获取设置失败=====', err)
              resolve(false)
            }
          })
        }
      } else {
        Taro.hideLoading()
        resolve(false)
      }
    })
  })
}

function requestSubscribe(templateIds) {
  return new Promise((resolve) => {
    Taro.requestSubscribeMessage({
      tmplIds: templateIds,
      entityIds: [],
      success: (res) => {
        console.log('订阅ffuucckk:', res, templateIds)

        // 点击拒绝
        if (res[templateIds[0]] === 'reject') {
          console.log('订阅ffuucckk: reject')
          Taro.eventCenter.trigger('requestSubscribeReject')
          resolve(false)
        } else {
          resolve(true)
        }
      },
      fail: (err) => {
        resolve(false)
        console.log('订阅ffuucckk2:', err)
      }
    })
  })
}
